                            # 8.1 定义函数
def greet_user():
    # 文档字符串注释，描述了函数是做什么的
    """显示简单的问候语"""
    print("Hello!") # 缩进行构成函数体
greet_user()
# 8.1.1 向函数传递信息
def greet_user(username):
    """显示简单的问候语"""
    print("Hello, " + username.title() + "!")

greet_user('howie hsu')
# 8.1.2 实参和形参
                            # 8.2 传递实参
# 8.2.1 位置实参
    # 最简单的关联方式是基于实参的顺序
def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet("hamster", "harry")
describe_pet('dog', 'whillie')
# 8.2.2 关键字实参
    # 传递给函数的是 名称-对, 此时顺序无关紧要
describe_pet(animal_type='cat', pet_name='kitty')
# 8.2.3 默认值
    # 必须先列出没有默认值的形参，再列出有默认值的形参
def describe_pet(pet_name,animal_type = 'dog'):
    """显示宠物的信息(默认值参数)"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('golf')
describe_pet('micky', 'mouse')
# 8.2.4 等效的函数调用
# 8.2.5 避免实参错误
                            # 8.3 返回值
# 8.3.1 返回简单值
def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)
# 8.3.2 让实参变成可选的
def get_formatted_name(first_name, last_name, middle_name = ''):
    """返回整洁的姓名"""
    # 并不是每个人都有中间名
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()

musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
# 8.3.3 返回字典
def build_person(first_name, last_name, age = ''):
    """返回一个字典，其中包含有关一个人的信息"""
    person = {
        'first': first_name,
        'last': last_name,
    }
    if age:
        person['age'] = age
    return person

musician = build_person('howie', 'hsu', 19)
print(musician)
# 8.3.4 结合使用函数和while循环
while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")

    f_name = input("First name: ")
    if f_name == 'q':
        break

    l_name = input("Last name: ")
    if l_name == 'q':
        break

    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name.title() + "!")
                            # 8.4 传递列表
def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
# 8.4.1 在函数中修改列表
    # 首先创建一个列表，其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
    # 模拟打印每个设计，直到没有未打印的设计为止
    #  打印每个设计后，都将其移到列表completed_models中
while unprinted_designs:
    current_design = unprinted_designs.pop()

    # 模拟根据设计制作3D打印模型的过程
    print("Printing model: " + current_design)
    completed_models.append(current_design)

    # 显示打印好的模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)
# 现在用函数重新组织这些代码
def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计，直到没有未打印的设计为止
    打印每个设计后，都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()

        # 模拟根据设计制作3D打印模型的过程
        print("Printing model: " + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
# 8.4.2 禁止函数修改列表
    # 调用函数的时候使用切片
    # function_name(list_name[:])
    # 这样使用的就是列表的副本，而不是列表本身
def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计，直到没有未打印的设计为止
    打印每个设计后，都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()

        # 模拟根据设计制作3D打印模型的过程
        print("Printing model: " + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs[:], completed_models)
show_completed_models(completed_models)

print("\nunprinted_designs:")
for unprinted_design in unprinted_designs:
    print(unprinted_design)
                            # 8.5 传递任意数量的实参
# 8.5.1 结合使用位置实参和任意数量实参
    # 适用于事先不知道函数需要接受多少个实参,必须放在最后
def make_pizza(size, *toppings): # 实质是创建一个名为toppings的元组，
                           # 并将收到的所有值装到这个元组中
    """打印顾客点的所有配料"""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 8.5.2 使用任意数量的关键字实参
# 形参**user_info创建一个字典，并将收到的所有名称-值对都封装到这个字典中
def build_profile(first, last, **user_info):
    """创建一个字典，其中包含我们知道的有关用户的一切"""
    profile = {}  # 创建空字典，用于存储用户简介
    profile['first_name'] = first  # 加入名
    profile['last_name'] = last  # 加入姓
    for key, value in user_info.items():  # 遍历字典user_info中的所有键-值对
        profile[key] = value  # 将每个键-值对加入到字典profile中
    return profile

user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             filed='physics')
print(user_profile)
                            # 8.6 将函数存储在模块中
# 8.6.1 导入整个模块
    # module.function_name()
import making_pizzas # 打开文件 making_pizzas.py，可以使用其中定义的所有函数

making_pizzas.make_pizza(16, 'pepperoni')
making_pizzas.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 8.6.2 导入特定的函数
    # from module_name import function_0, funciton_1, function_3
from making_pizzas import make_pizza

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 8.6.3 使用as给函数指定别名
    # 导入的函数可能与程序中现有的名称冲突，或者函数名称太长
from making_pizzas import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
# 8.6.4 使用as给模块指定别名
    # 更轻松地调用其中的函数
import making_pizzas as p

p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 8.6.5 导入模块中的所有函数
    # from module_name import *
from making_pizzas import *

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
                            # 8.7 函数编写指南